﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Json;

namespace Aliyun.OSS.Sdk.JSST
{
    /// <summary>
    /// Json序列化
    /// 张睿 2017-10-30
    /// </summary>
    public class JsonHelper
    {
        /// <summary>
        /// 序列化为Json
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="t">对象</param>
        /// <returns></returns>
        public static string JsonSerialize<T>(T t)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            ser.WriteObject(ms, t);

            string str = Encoding.UTF8.GetString(ms.ToArray());

            return str;
        }

        /// <summary>
        /// Json反序列化为对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="json">Json对象</param>
        /// <returns>反序列化对象</returns>
        public static T JsonDeserialize<T>(string json)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            System.IO.MemoryStream ms = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(json));
            T t = (T)ser.ReadObject(ms);

            return t;
        }
    }
}
